package com.ecommerce.service;

import com.ecommerce.constant.AsyncTaskStatusEnum;
import com.ecommerce.goods.GoodsInfo;
import com.ecommerce.service.async.AsyncService;
import com.ecommerce.vo.AsyncTaskInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 异步任务执行管理器：对异步任务进行包装管理，记录异步任务执行信息
 */
@Slf4j
@Component
public class AsyncTaskManager {

    // 异步任务执行信息的容器
    private final Map<String, AsyncTaskInfo> taskContainer = new HashMap<>(16);

    private final AsyncService asyncService;

    public AsyncTaskManager(AsyncService asyncService) {
        this.asyncService = asyncService;
    }

    /**
     * 初始化异步任务
     */
    public AsyncTaskInfo initTask() {
        AsyncTaskInfo asyncTaskInfo = new AsyncTaskInfo();
        // 设置一个唯一的异步任务Id, 只要唯一即可
        asyncTaskInfo.setTaskId(UUID.randomUUID().toString());
        asyncTaskInfo.setStatus(AsyncTaskStatusEnum.STARTED);
        asyncTaskInfo.setStartTime(new Date());

        // 初始化时就要把异步任务执行信息放入到存储容器中
        taskContainer.put(asyncTaskInfo.getTaskId(), asyncTaskInfo);

        return asyncTaskInfo;
    }

    /**
     * 提交异步任务
     */
    public AsyncTaskInfo submit(List<GoodsInfo> goodsInfos) {
        // 初始化异步任务的监控信息
        AsyncTaskInfo asyncTaskInfo = initTask();
        asyncService.asyncImportGoods(goodsInfos, asyncTaskInfo.getTaskId());
        return asyncTaskInfo;
    }

    /**
     * 设置异步任务执行状态信息
     */
    public void setTaskInfo(AsyncTaskInfo asyncTaskInfo) {
        taskContainer.put(asyncTaskInfo.getTaskId(), asyncTaskInfo);
    }

    /**
     * 获取异步任务执行信息
     */
    public AsyncTaskInfo getTaskInfo(String taskId) {
        return taskContainer.get(taskId);
    }
}
